package com.xxx.car.web.api;

import com.xxx.car.constants.MsgStatus;
import com.xxx.car.entity.vo.request.ReqUserMsgDel;
import com.xxx.car.entity.vo.request.ReqUserMsgGet;
import com.xxx.car.entity.vo.request.ReqUserMsgQuery;
import com.xxx.car.entity.vo.response.RespUserMsg;
import com.xxx.car.service.UserMsgService;
import com.xxx.common.base.enums.ApiResponseEnum;
import com.xxx.common.base.vo.APIResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * Created by xuwenjie on 2017/6/14.
 */
@Controller
@RequestMapping("/api/msg")
public class ApiUserMsgController {

    private final static Logger LOG = LoggerFactory.getLogger(ApiUserMsgController.class);

    @Autowired
    private UserMsgService userMsgService;

    @RequestMapping("/list")
    @ResponseBody
    public APIResponse list(@Valid @ModelAttribute ReqUserMsgQuery query, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        List<RespUserMsg> list = userMsgService.findByPage(query);
        return APIResponse.returnSuccess(list);
    }

    @RequestMapping("/get")
    @ResponseBody
    public APIResponse get(@Valid @ModelAttribute ReqUserMsgGet userMsgGet, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        RespUserMsg msg = userMsgService.getByIdAndUser(userMsgGet.getUserId(), userMsgGet.getMsgId());
        if (msg != null && msg.getMsgStatus() != MsgStatus.HAS_READ) {
            userMsgService.modifyStatus(userMsgGet.getMsgId(), MsgStatus.HAS_READ);
        }
        return APIResponse.returnSuccess(msg);
    }

    @RequestMapping("/del")
    @ResponseBody
    public APIResponse del(@Valid @ModelAttribute ReqUserMsgDel reqUserMsgDel, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        userMsgService.delteByIdAndUser(reqUserMsgDel.getUserId(), Arrays.asList(reqUserMsgDel.getMsgId()));
        return APIResponse.returnSuccess();
    }

}
